<template>
  <div class="xgplayer-container">
    <div ref="playerContainer" class="player-wrapper"></div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onBeforeUnmount,
  watch,
  defineProps,
  defineEmits,
  defineExpose,
  nextTick,
} from "vue";
import Player from "xgplayer";
import HlsPlugin from "xgplayer-hls";
import FlvPlugin from "xgplayer-flv";
import "xgplayer/dist/index.min.css";

// 组件属性
const props = defineProps({
  // 视频流地址
  url: {
    type: String,
    required: true,
    default: "",
  },
  // 播放器配置
  config: {
    type: Object,
    default: () => ({}),
  },
  // 是否自动播放
  autoplay: {
    type: Boolean,
    default: false,
  },
  // 播放器宽度
  width: {
    type: [String, Number],
    default: "100%",
  },
  // 播放器高度
  height: {
    type: [String, Number],
    default: "100%",
  },
});

// 组件事件
const emit = defineEmits([
  "ready",
  "play",
  "pause",
  "ended",
  "error",
  "loadstart",
  "canplay",
]);

// 响应式数据
const playerContainer = ref(null);
let player = null;

// 根据URL判断视频格式类型
const getVideoType = (url) => {
  if (!url) return "mp4";

  const lowerUrl = url.toLowerCase();

  if (lowerUrl.includes(".m3u8") || lowerUrl.includes("hls")) {
    return "hls";
  } else if (lowerUrl.includes(".flv") || lowerUrl.includes("flv")) {
    return "flv";
  } else {
    return "mp4";
  }
};

// 获取对应格式的插件配置
const getPluginConfig = (type) => {
  const plugins = [];

  switch (type) {
    case "hls":
      plugins.push(HlsPlugin);
      break;
    case "flv":
      plugins.push(FlvPlugin);
      break;
    default:
      // mp4格式使用默认播放器，不需要额外插件
      break;
  }

  return plugins;
};

// 初始化播放器
const initPlayer = () => {
  if (!props.url || !playerContainer.value) {
    console.warn("播放器初始化失败：缺少URL或DOM容器");
    return;
  }

  const videoType = getVideoType(props.url);
  const plugins = getPluginConfig(videoType);

  console.log("检测到视频格式:", videoType);
  console.log(
    "使用插件:",
    plugins.map((p) => p.name || p.pluginName || "unknown")
  );

  // 播放器基础配置
  const playerConfig = {
    el: playerContainer.value,
    url: props.url,
    autoplay: props.autoplay,
    width: props.width,
    height: props.height,
    poster: "",
    playsinline: true,
    controls: true,
    fluid: true,
    ...props.config,
  };

  console.log("播放器配置:", playerConfig);

  // 添加插件
  if (plugins.length > 0) {
    playerConfig.plugins = plugins;
  }

  try {
    player = new Player(playerConfig);

    // 绑定事件监听
    bindEvents();

    console.log(`视频播放器初始化成功，格式：${videoType}`);
  } catch (error) {
    console.error("播放器初始化失败:", error);
    emit("error", error);
  }
};

// 绑定播放器事件
const bindEvents = () => {
  if (!player) return;

  player.on("ready", () => {
    console.log("播放器准备就绪");
    emit("ready", player);
  });

  player.on("play", () => {
    console.log("开始播放");
    emit("play");
  });

  player.on("pause", () => {
    console.log("暂停播放");
    emit("pause");
  });

  player.on("ended", () => {
    console.log("播放结束");
    emit("ended");
  });

  player.on("error", (error) => {
    console.error("播放器错误:", error);
    emit("error", error);
  });

  player.on("loadstart", () => {
    console.log("开始加载");
    emit("loadstart");
  });

  player.on("canplay", () => {
    console.log("可以播放");
    emit("canplay");
  });
};

// 播放
const play = () => {
  if (player) {
    player.play();
  }
};

// 暂停
const pause = () => {
  if (player) {
    player.pause();
  }
};

// 重新加载
const reload = () => {
  if (player) {
    const currentTime = player.currentTime || 0;
    player.src = props.url;
    player.load();
    // 尝试恢复到之前的播放位置
    setTimeout(() => {
      if (currentTime > 0) {
        player.currentTime = currentTime;
      }
    }, 1000);
  }
};

// 销毁播放器
const destroyPlayer = () => {
  if (player) {
    try {
      player.destroy();
      player = null;
      console.log("播放器已销毁");
    } catch (error) {
      console.error("销毁播放器失败:", error);
    }
  }
};

// 获取播放器实例
const getPlayer = () => {
  return player;
};

// 监听URL变化，重新初始化播放器
watch(
  () => props.url,
  (newUrl, oldUrl) => {
    if (newUrl !== oldUrl) {
      destroyPlayer();
      if (newUrl && playerContainer.value) {
        nextTick(() => {
          initPlayer();
        });
      }
    }
  }
);

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    // 确保DOM和props都准备就绪
    if (playerContainer.value && props.url) {
      initPlayer();
    } else if (props.url) {
      // 如果URL存在但DOM还没准备好，稍后重试
      setTimeout(() => {
        if (playerContainer.value) {
          initPlayer();
        }
      }, 100);
    }
  });
});

onBeforeUnmount(() => {
  destroyPlayer();
});

// 对外暴露的方法
defineExpose({
  play,
  pause,
  reload,
  getPlayer,
  destroyPlayer,
});
</script>

<style scoped>
.xgplayer-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.player-wrapper {
  width: 100%;
  height: 100%;
  background: #000;
  border-radius: 4px;
  overflow: hidden;
}

/* 自定义播放器样式 */
:deep(.xgplayer) {
  font-family: "Alibaba PuHuiTi", "PingFang SC", "Microsoft YaHei", Arial,
    sans-serif;
  width: 100% !important;
  height: 100% !important;
}

:deep(.xgplayer-controls) {
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.5));
}

:deep(.xgplayer-play) {
  color: #fff;
}

:deep(.xgplayer-time) {
  color: #fff;
  font-size: 12px;
}

:deep(.xgplayer-progress) {
  height: 4px;
}

:deep(.xgplayer-progress-played) {
  background: #409eff;
}

:deep(.xgplayer-volume-control) {
  color: #fff;
}
</style>
